package com.zcoj.codeSimilar.service.impl;

import com.zcoj.codeSimilar.service.ExecuteCodeSimilarService;
import com.zcoj.codeSimilar.service.SubmitCodeContrastService;
import com.zcoj.pojo.Dto.Contest;
import com.zcoj.pojo.Dto.ContestProblem;
import com.zcoj.pojo.Dto.Judge;
import com.zcoj.service.ContestProblemService;
import com.zcoj.service.ContestService;
import com.zcoj.service.JudgerService;
import com.zcoj.util.RedisCaches;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author chenbin
 * @version 1.0
 * @description: TODO
 * @date 2023/8/5 12:41
 */
@Service
@Slf4j
public class SubmitCodeContrastServiceImpl implements SubmitCodeContrastService {

	@Autowired
	private RedisCaches redisCaches;

	@Autowired
	private ContestService contestService;

	@Autowired
	private JudgerService judgerService;

	@Autowired
	private ContestProblemService contestProblemService;

	@Autowired
	private ExecuteCodeSimilarService executeCodeSimilarService;

	@Override
	public Map<Integer, String> canSubmitCodeContrast(Integer cid) {
		Map<Integer, String> objectObjectMap = new HashMap<>();
		if(!checkContestEnd(cid)){
			String codeSimilarityCidKey="codeSimilarityCidKey::"+cid;
			Object cacheObject = redisCaches.getCacheObject(codeSimilarityCidKey);
			if (Objects.isNull(cacheObject)){
				//key不存在 则进行提交检测
				objectObjectMap.put(1,"正在进行相似度检测，请稍等");
				submitCodeContrast(cid);
			}else {
				objectObjectMap.put(0,"正在进行相似度检测，请不要重复提交");
			}

		}else {
			objectObjectMap.put(-1,"参数错误，请使用正确参数");
		}
		return objectObjectMap;
	}

	/**
	 * @method: [submitCodeContrast]
	 * @param: [cid]
	 * @returns: void
	 * @description:  将测评记录中的测评数据统计
	 * @author: chen.bin
	 * @version: 1.0.0
	 * @date 2023/8/5 13:17
	 **/
	@Override
	public void submitCodeContrast(Integer cid) {
		ContestProblem contestProblem = new ContestProblem();
		contestProblem.setCid(cid);
		List<ContestProblem> contestProblemServiceList = contestProblemService.findList(contestProblem);
		String codeSimilarityCidKey="codeSimilarityCidKey::"+cid;
		redisCaches.setCacheObject(codeSimilarityCidKey,cid);
		log.info("进入submitCodeContrast");
		for (ContestProblem problem : contestProblemServiceList) {
			Integer pid = problem.getPid();
			Judge judge = new Judge();
			judge.setCid(cid);
			judge.setStatus(0);
			judge.setPid(pid);
			List<Judge> judgeList = judgerService.findList(judge);
			executeCodeSimilarService.contrastCode(pid,cid,judgeList);
		}
	}

	@Override
	public Boolean checkContestEnd(Integer cid) {
		Contest contestTime = contestService.getContestTime(cid);
		if(Objects.nonNull(contestTime)){
			long time = contestTime.getEndTime().getTime();
			//检测比赛是否结束
			return time-new Date().getTime()>0;
		}
		return true;
	}
}
